package com.example.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;

@RestController
@RequestMapping("/kaptcha")
public class KaptchaController {
    private static final Logger logger = LogManager.getLogger(KaptchaController.class);

    @Autowired
    DefaultKaptcha defaultKaptcha;

    @GetMapping("/get")
    public void kaptcha(HttpServletRequest req, HttpServletResponse rsp) throws Exception {
        HttpSession session = req.getSession();
        String code = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);

        rsp.setDateHeader("Expires", 0);
        rsp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        rsp.addHeader("Cache-Control", "post-check=0, pre-check=0");
        rsp.setHeader("Pragma", "no-cache");
        rsp.setContentType("image/jpeg");

        String capText = defaultKaptcha.createText();
        logger.info("old 图形验证码: " + code + "，新的图形验证码: " + capText);

        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);

        BufferedImage image = defaultKaptcha.createImage(capText);
        ServletOutputStream out = rsp.getOutputStream();
        ImageIO.write(image, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }

    /**
     * 验证验证码
     *
     * @param request
     * @return
     */
    @GetMapping("/verify")
    @ResponseBody
    public Object verifyCode(HttpServletRequest request) {
        String code = request.getParameter("code");
        if (StringUtils.isEmpty(code)){
            return "请输入验证码";
        }
        HttpSession session = request.getSession();
        String vcode = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        logger.info("old 图形验证码: " + vcode);

        if (code.equalsIgnoreCase(vcode)){
            // session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);

            return "验证成功";
        }
        return "验证失败";
    }


}